﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Nature.Text
{
    public class TextFormatException : FormatException
    {
        readonly Lazy<string> m_message;
        readonly List<TextInfoEventArgs> m_errors;

        internal TextFormatException(IEnumerable<TextInfoEventArgs> args)
        {
            m_errors = args.OrderBy(i=> i.Fragment).ToList();
            m_message = new Lazy<string>(() => {
                var message = new StringBuilder();
                foreach (var err in m_errors) 
                {
                    var position = err.Fragment.Source[err.Fragment.Index];
                    message.AppendFormat("Line: {0}, column: {1}, Message: {2}", position.Line, position.Column, err.Message );
                    message.AppendFormat("\r\n{0}", position.ToString());
                }
                return message.ToString();
            });
        }

        public IEnumerable<TextInfoEventArgs> Errors
        {
            get { return new ReadOnlyCollection<TextInfoEventArgs>(m_errors); }
        }

        public override string Message
        {
            get { return m_message.Value; }
        }
    }
}
